package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 用户登录接口
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());
        //去数据库搜索是否存在openid,不存在就新增一条
        User user = userMapper.queryByOpenid(openid);
        if (Objects.isNull(user)){
            user = new User();
            BeanUtils.copyProperties(userLoginDTO, user);
            user.setOpenid(openid);
            userMapper.insertUser(user);
        }
        //jwt生成token
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        UserLoginVO u = UserLoginVO.builder().id(user.getId()).token(token).openid(openid).build();
        return u;

    }

    //将获取openid的代码抽取成一个方法
    private String  getOpenid(String  code) {
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type", weChatProperties.getAppid());
        //调用工具类，拿到openid
        String json = HttpClientUtil.doGet(weChatProperties.getJscode2sessionUrl(),paramMap);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        //如果openid为null，一般是前端传入参数错误，抛异常
        if (Objects.isNull(openid)){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        return openid;
    }
}
